package javase.base;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 多线程输出素数
 * 
 * @Package javase
 * @ClassName: CalculatePrimes
 * @author Realfighter
 * @date 2014-7-10 下午03:26:02
 */
public class CalculatePrimesByTimer extends Thread {

	public static final int MAX_PRIMES = 1000000;// 输入1000000个

	public static final int TEN_SECONDS = 10000;// 主线程休息10秒

	public volatile boolean finished = false;// 主线程是否被唤醒

	@Override
	public void run() {
		int[] primes = new int[MAX_PRIMES];
		int count = 0;
		for (int i = 2; count < MAX_PRIMES; i++) {
			if (finished) {
				break;
			}
			boolean prime = true;
			for (int j = 0; j < count; j++) {
				if (i % primes[j] == 0) {
					prime = false;
					break;
				}
			}
			if (prime) {
				primes[count++] = i;
				System.out.println("Found Prime：" + i);
			}
		}
	}

	public static void main(String[] args) {
		Timer timer = new Timer();
		final CalculatePrimesByTimer calculatePrimes = new CalculatePrimesByTimer();
		calculatePrimes.start();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				calculatePrimes.finished = true;
			}

		}, TEN_SECONDS);
	}

}
